package com.xinting.piano.lib.storage;

import android.os.Environment;
import android.util.Log;

import java.io.File;
import java.io.IOException;

/**
 * Created by wuxinting on 15/10/30.
 */
public class PStorage {

    private static PStorage storage;

    public static final String ROOT_DIR = "piano";

    public static PStorage getInstance() {
        if (storage == null) {
            synchronized (PStorage.class) {
                if (storage == null) {
                    storage = new PStorage();
                }
            }
        }
        return storage;
    }

    /**
     * 获取本应用的根目录
     * @return
     */
    public File getAppRootDir() {
        File music = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC);
        File root = new File(music, ROOT_DIR);
        if (!root.exists()) {
            root.mkdirs();
        }
        return root;
    }

    /**
     * 获取某个文件实例，如果该文件不存在会自动创建
     * @param name 文件名
     * @return
     */
    public File getFile(String name) throws IOException {
        File file = new File(getAppRootDir(), name);
        Log.v("piano", file.getAbsolutePath());
        if (!file.exists()) {
            file.createNewFile();
        }
        file.setWritable(true);
        return file;
    }

    /* Checks if external storage is available for read and write */
    public boolean isExternalStorageWritable() {
        String state = Environment.getExternalStorageState();
        if (Environment.MEDIA_MOUNTED.equals(state)) {
            return true;
        }
        return false;
    }

    /* Checks if external storage is available to at least read */
    public boolean isExternalStorageReadable() {
        String state = Environment.getExternalStorageState();
        if (Environment.MEDIA_MOUNTED.equals(state) ||
                Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
            return true;
        }
        return false;
    }
}
